<script lang="ts">
    import { getGravatarFromCurrentUserSrc } from '$api/gravatar';
    import { getMeQuery } from '$api/usersApi';
    import { derived } from 'svelte/store';

    import * as Avatar from '$comp/ui/avatar';
    import ErrorMessage from '$comp/ErrorMessage.svelte';
    import EmailInput from '$comp/form/EmailInput.svelte';
    import TextInput from '$comp/form/TextInput.svelte';
    import { Separator } from '$comp/ui/separator';
    import { Button } from '$comp/ui/button';
    import Loading from '$comp/Loading.svelte';
    import H3 from '$comp/typography/H3.svelte';
    import Muted from '$comp/typography/Muted.svelte';

    const userResponse = getMeQuery();
    const gravatarSrc = getGravatarFromCurrentUserSrc(userResponse);

    const generalError = derived(userResponse, ($userResponse) => {
        return $userResponse.error?.message as string | undefined;
    });

    async function onSave() {
        // await userResponse.mutate({
        //     full_name: userResponse.data.full_name,
        //     email_address: userResponse.data.email_address,
        // });
    }
</script>

<div class="space-y-6">
    <div>
        <H3>Account</H3>
        <Muted>Manage your account settings and set e-mail preferences.</Muted>
    </div>
    <Separator />

    <Avatar.Root title="Profile Image" class="h-24 w-24">
        {#await $gravatarSrc}
            <Avatar.Fallback><Loading /></Avatar.Fallback>
        {:then src}
            <Avatar.Image {src} alt="gravatar" />
        {:catch}
            <Avatar.Fallback>Error</Avatar.Fallback>
        {/await}
    </Avatar.Root>
    <Muted>Your avatar is generated by requesting a Gravatar image with the email address below.</Muted>

    <form on:submit|preventDefault={onSave} class="space-y-2">
        <ErrorMessage message={$generalError}></ErrorMessage>
        {#if $userResponse.data}
            <TextInput name="full_name" label="Full Name" bind:value={$userResponse.data.full_name} autocomplete="name" required problem={$userResponse.error}
            ></TextInput>
            <EmailInput
                name="email_address"
                label="Email Address"
                bind:value={$userResponse.data.email_address}
                autocomplete="email"
                required
                problem={$userResponse.error}
            ></EmailInput>
        {/if}
        <div class="pt-2">
            <Button type="submit">
                {#if $userResponse.isLoading}
                    <Loading class="mr-2" variant="secondary"></Loading> Saving...
                {:else}
                    Save
                {/if}
            </Button>
        </div>
    </form>
</div>
